<?php

class Model_User extends Model_Database
{
	var $table = 'user';
	
	public function check_param($data){
		$email_len = UTF8::strlen($data['email']);
		if (!empty($data['email']) && ($email_len > 100 || !Valid::email($data['email']))){
			return '邮箱错误';
		}
		
		$con_len = UTF8::strlen($data['content']);
		if ($con_len < 5 || $con_len > 500){
			return '内容错误';
		}
		
		return true;
	}
	
	public function get_list($uid = -1, $status = -1, $offset = 0, $limit = 20){
		$where_arr = array();
		if ($uid > -1){
			$where_arr[] = "uid={$uid}";
		}
		if ($status > -1){
			$where_arr[] = "status={$status}";
		}
		
		$where = 'where del=0';
		if (!empty($where_arr)){
			$where .= ' and ' . implode(' and ', $where_arr);
		}
		
		$sql = 'select uid, user, password, nick, email, regip, addtime, uptime, loginip, logintime, ';
		$sql .= 'status, gender, birthday, phone, qq, district ';
		$sql .= "from {$this->table} {$where} order by uid desc limit {$offset}, {$limit}";
		
		$re = $this->_db->query(Database::SELECT, $sql);
    	return $re->as_array();
	}
	
	public function check($user, $password){
		$password = $this->generate_password($user, $password);
		$sql = "select uid from {$this->table} where status=0 and del=0 and user='{$user}' and password='{$password}'";
		$re = $this->_db->query(Database::SELECT, $sql);
    	$num = $re->count();
    	return ($num > 0) ? true : false;
	}
	
	public function add($data){
		$user = addslashes(trim($data['user']));
		$password = $this->generate_password($user, $data['password']);
		$email = addslashes(trim($data['email']));
		$regip = $data['regip'];
		$addtime = date('Y-m-d H:i:s');
		
		$sql = "insert into {$this->table} (user, password, email, regip, addtime, status) ";
		$sql .= "values('{$user}', '{$password}', '{$email}', '{$regip}', '{$addtime}')";
		return $this->_db->query(Database::INSERT, $sql);
	}
	
	public function update($data, $uid){
		$val_arr = array();
		foreach ($data as $key => $record){
			$val_arr[] = "{$key}='{$record}'";
		}
		$val_str = implode(',', $val_arr);
		$sql = "update {$this->table} set {$val_str} where uid={$uid}";
		return $this->_db->query(Database::UPDATE, $sql);
	}
	
	public function del($uid){
		$uid = is_array($uid) ? implode(',', $uid) : $uid;
		$sql = "update {$this->table} set del=1 where uid in ({$uid})";
		return $this->_db->query(Database::UPDATE, $sql);
	}
	
	private function generate_password($user, $password){
		return md5(md5($user . $password) . $password);
	}
	
}
